import numpy as np
import matplotlib.pyplot as plt
def loadDataSet (filename):
    dataSet = []
    fr = open(filename)
    for line in fr.readlines():
        curline = line.split('\t')
        fltLine = list(map(float, curline))
        #print(fltLine)
        dataSet.append(fltLine)
    return dataSet
def distElub(vecA, vecB):#平方和
    return np.sqrt(np.sum(np.power(vecA-vecB, 2)))
def randCent(dataSet, k):
    n = np.shape(dataSet)[1]
    #print(n)
    centroids = np.mat(np.zeros((k, n)))
    for j in range(n):
        minJ = min(dataSet[:,j])
        #每列最小值
        #print(minJ)
        #每列最大值和最小值之差
        rangeJ = float(max(dataSet[:, j]) - minJ)
        centroids[:,j] = minJ + rangeJ * np.random.rand(k, 1)
    return centroids
def kMeans(dataSet, k, disMeas=distElub, createCent=randCent):
    m = np.shape(dataSet)[0]
    #定义一个全0矩阵
    clusterAssment = np.mat(np.zeros((m, 2)))
    centroids = createCent(dataSet, k)
    clustterChanged = True
    while clustterChanged:
        clustterChanged = False
        for i in range(m):
            minDist = float('inf')
            inIndex = -1
            for j in range(k):
                #计算点到质心的距离
                distJI = disMeas(centroids[j,:], dataSet[i,:])
                if distJI < minDist:
                    minDist = distJI
                    minIndex = j
            if clusterAssment[i, 0] != minIndex:
                clustterChanged = True
            clusterAssment[i, :]=minIndex,minDist**2
        print(centroids)
        for cent in range(k):
            ptsInClust = dataSet[np.nonzero(clusterAssment[:,0].A==cent)[0]]
            #求取均值
            centroids[cent,:] = np.mean(ptsInClust, axis=0)
    return centroids, clusterAssment
def plotDataSet(filename):
    # 导入数据
    datMat = np.mat(loadDataSet(filename))
    # 进行k-means算法其中k为4
    myCentroids, clustAssing = kMeans(datMat, 4)
    clustAssing = clustAssing.tolist()
    myCentroids = myCentroids.tolist()
    xcord = [[], [], [], []]
    ycord = [[], [], [], []]
    datMat = datMat.tolist()
    m = len(clustAssing)
    for i in range(m):
        if int(clustAssing[i][0]) == 0:
            xcord[0].append(datMat[i][0])
            ycord[0].append(datMat[i][1])
        elif int(clustAssing[i][0]) == 1:
            xcord[1].append(datMat[i][0])
            ycord[1].append(datMat[i][1])
        elif int(clustAssing[i][0]) == 2:
            xcord[2].append(datMat[i][0])
            ycord[2].append(datMat[i][1])
        elif int(clustAssing[i][0]) == 3:
            xcord[3].append(datMat[i][0])
            ycord[3].append(datMat[i][1])
    fig = plt.figure()
    ax = fig.add_subplot(111)
    # 绘制样本点
    ax.scatter(xcord[0], ycord[0], s=20, c='b', marker='*', alpha=.5)
    ax.scatter(xcord[1], ycord[1], s=20, c='r', marker='D', alpha=.5)
    ax.scatter(xcord[2], ycord[2], s=20, c='c', marker='>', alpha=.5)
    ax.scatter(xcord[3], ycord[3], s=20, c='k', marker='o', alpha=.5)
    # 绘制质心
    ax.scatter(myCentroids[0][0], myCentroids[0][1], s=100, c='k', marker='+', alpha=.5)
    ax.scatter(myCentroids[1][0], myCentroids[1][1], s=100, c='k', marker='+', alpha=.5)
    ax.scatter(myCentroids[2][0], myCentroids[2][1], s=100, c='k', marker='+', alpha=.5)
    ax.scatter(myCentroids[3][0], myCentroids[3][1], s=100, c='k', marker='+', alpha=.5)
    plt.title('DataSet')
    plt.xlabel('X')
    plt.show()
'''dataMat = np.mat(loadDataSet("testSet.txt"))
#print (dataMat)
#print (min(dataMat[:,0]))
print(dataMat[1,:])
centroids=randCent(dataMat, 2)
print(centroids)'''
#plotDataSet("testSet.txt")
da = np.random.rand(2, 1)
print (da)